/*
 * @Author: linxun 
 * @Date: 2021-03-06 17:22:15 
 * @Last Modified by: linxun
 * @Last Modified time: 2021-07-26 17:03:42
 * @Description: 制作数据集-第二步
 */

import React, { useState, useRef, Fragment, useImperativeHandle, forwardRef } from 'react';
import { Form, Radio, Upload, Input, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { useIntl } from 'umi';
import moment from 'moment';
import { FORMLAYOUT_1 } from '@/utils/const';
import { FilePathReg } from '@/utils/reg';
import { bizCodeMessage } from '@/utils/errCode';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Dragger } = Upload;

export const addonBeforePath = '/data/dataset/';

const SecondStep = (props, ref) => {
  const { formatMessage } = useIntl();
  const [form] = Form.useForm();
  const { setDisabled, createSourceType, hideWithAnnotFile } = props;
  const [fileList, setFileList] = useState([]);
  const initialValues = {
    sourceType: 'upload_from_page',
    selectWay: 1,
    withAnnotFile: false,
  };

  const uploadProps = {
    name: 'file',
    // multiple: true,
    // fileList: fileList,
    // accept: 'application/zip, application/x-gzip, application/x-tar',
    action: '/file_server/api/v1/files',
    data: (file) => ({
      modId: 'songshanhu',
      objectName: file.name,
    }),
    headers: {
      Authorization: 'Bearer ' + window.localStorage.token,
    },
    progress: {
      format: percent => `${parseFloat(percent.toFixed(2))}%`
    },
    maxCount: 1,
    beforeUpload: file => {
      const { type, size, name } = file;
      const typeReg = /\.(zip|tar|gz)$/;
      return new Promise((resolve, reject) => {
        if (fileList.length && fileList.findIndex((i) => i.name === name) > -1) {
          message.warning(`${formatMessage({ id: 'dataSet.create.tips.upload.equalFile' })}`);
          reject(file);
        }
        if (!typeReg.test(name)) {
          message.warning(
            `${formatMessage({ id: 'dataSet.create.tips.upload.supportFile' })}`,
          );
          reject(file);
        }
        resolve(file);
      });
    },
    onChange: info => {
      const { file } = info;
      const { status, name } = file;
      setDisabled(true);
      if (status === 'done') {
        setDisabled(false);
        const code = file.response?.code;
        if (code === 0) {
          message.success(
            `${name} ${formatMessage({ id: 'dataSet.create.tips.upload.success' })}！`,
          );
        } else {
          const errMsg = bizCodeMessage[code] || '文件上传失败，请重试！';
          message.error(errMsg);
        }
      } else if (status === 'error') {
        message.error(`${name} ${formatMessage({ id: 'dataSet.create.tips.upload.error' })}`);
        setDisabled(false);
      }
      form.setFieldsValue({ fileList: info.fileList });
      setFileList(info.fileList);
    },
    onRemove: file => {
      let newFileList = fileList;
      newFileList.splice(
        fileList.findIndex((i) => i.uid === file.uid),
        1,
      );
      form.setFieldsValue({ fileList: [...newFileList] });
      setFileList([...newFileList]);
    },
  };

  const formFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 暴露给父组件
  useImperativeHandle(ref, () => ({
    secondForm: form,
  }));

  return (
    <Form form={form} scrollToFirstError initialValues={initialValues} {...FORMLAYOUT_1}>
      <FormItem
        label={formatMessage({ id: 'dataSetCreate.label.sourceType' })}
        rules={[{ required: true }]}
        name='sourceType'
      >
        <RadioGroup>
          {createSourceType.map(item => (
            <Radio key={item.value} value={item.value}>{item.label}</Radio>
          ))}
        </RadioGroup>
      </FormItem>
      {!hideWithAnnotFile &&
        <FormItem shouldUpdate noStyle>
          {({ getFieldValue }) => (
            (getFieldValue('sourceType') === 'upload_from_page' || getFieldValue('sourceType') === 'import_from_path') ? (
              <FormItem
                label='是否包含标注信息'
                rules={[{ required: true }]}
                name='withAnnotFile'
              >
                <RadioGroup>
                  <Radio key={0} value={false}>否</Radio>
                  <Radio key={1} value={true}>是</Radio>
                </RadioGroup>
              </FormItem>
            ) : null
          )}
        </FormItem>
      }
      <FormItem shouldUpdate>
        {({ getFieldValue }) => (
          getFieldValue('sourceType') === 'make_from_files' ? (
            <Fragment>
              <FormItem
                label={formatMessage({ id: 'dataSet.dataSet.edit.selectRowDataType' })}
                rules={[{ required: true }]}
                extra={formatMessage({ id: 'dataSet.dataSet.edit.selectRowDataType.descr' })}
                name='selectWay'
              >
                <RadioGroup>
                  <Radio value={1}>
                    {formatMessage({ id: 'dataSet.dataSet.edit.selectRowDataType.byFilter' })}
                  </Radio>
                  <Radio value={2}>
                    {formatMessage({ id: 'dataSet.dataSet.edit.selectRowDataType.byManual' })}
                  </Radio>
                </RadioGroup>
              </FormItem>
            </Fragment>
          ) : (
            <Fragment>
              {getFieldValue('sourceType') === 'upload_from_page' && (
                <FormItem
                  label={formatMessage({ id: 'dataSetCreate.label.fileLists' })}
                  name='fileList'
                  rules={[
                    { required: true, message: formatMessage({ id: 'dataSetCreate.rule.needFile' }) },
                  ]}
                  valuePropName='fileList'
                  getValueFromEvent={formFile}
                  extra={<div style={{ marginTop: 12 }}>压缩文件要求对图片所在文件夹进行压缩或者直接对图片进行压缩，图片文件夹最多一层，不支持多层目录</div>}
                >
                  <Dragger {...uploadProps} style={fileList.length < 1 ? {} : { display: 'none' }}>
                    <p className='ant-upload-drag-icon'>
                      <InboxOutlined />
                    </p>
                    <p className='ant-upload-text'>
                      {formatMessage({ id: 'dataSetCreate.value.tips' })}
                    </p>
                    <p className='ant-upload-hint'>
                      {formatMessage({ id: 'dataSetCreate.value.tips.desc' })}
                    </p>
                  </Dragger>
                </FormItem>
              )}
              {getFieldValue('sourceType') === 'import_from_path' && (
                <FormItem
                  label={formatMessage({ id: 'dataSetCreate.label.path' })}
                  name='storagePath'
                  rules={[
                    {
                      required: true,
                      message: formatMessage({ id: 'dataSetCreate.rule.needStorePath' }),
                    },
                    { ...FilePathReg },
                  ]}
                  extra={<div style={{ marginTop: 12 }}>填写的路径必须为平台存储服务器下图片所在的路径，创建数据集后，该目录及图片会被移动到指定路径，请到数据集详情中查看路径信息。</div>}
                  // extra={<div style={{ marginTop: 12 }}>填写的路径必须为平台存储服务器下图片所在的路径，且图片文件夹最多一层，不支持多层目录；创建数据集后，该目录及图片会被移动到指定路径，请到数据集详情中查看路径信息。</div>}
                >
                  <Input
                    addonBefore={addonBeforePath}
                    placeholder={formatMessage({ id: 'dataSetCreate.placeholder.inputStorePath' })}
                  />
                </FormItem>
              )}
            </Fragment>
          ))}
      </FormItem>
    </Form>
  )
}

export default forwardRef(SecondStep);